#####################################################
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# FileName: my_monitor.py
# Description: 每五秒向influx数据库写入cpu,memory,disk,network占用率
# Version: 1.0
# Author: 管一鸣
# Date: 2022-05-15
# Platform: ubuntu
#####################################################
import time
import socket
import psutil


# 获取本机IP
def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 0))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP


ip = get_ip()


def get_all():
    cpu_info = psutil.cpu_percent(1)
    memory_info = psutil.virtual_memory()
    disk_info = psutil.disk_usage('/')
    network_if_addr = psutil.net_if_addrs()
    network_need = ""
    for item in network_if_addr:
        if network_if_addr.get(item)[0].address == ip:
            network_need = item
    network_info = psutil.net_io_counters(pernic=True)[network_need]
    network_percent = float(network_info.bytes_sent) / float(network_info.bytes_recv) * 100
    network_percent = round(network_percent, 2)
    text = [
        {
            "measurement": "all_info",
            "tags": {
                "host": ip
            },
            "fields": {
                "cpu_percent": cpu_info,
                "mem_percent": memory_info.percent,
                "disk_percent": disk_info.percent,
                "network_percent": network_percent,
            }
        }
    ]
    print(text)


if __name__ == '__main__':
    get_all()